package com.qiku.filter;

import com.qiku.entity.LoginUser;
import com.qiku.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取请求头的token
        String token = request.getHeader("token");
        //如果没有token  说明接口不需要登录 直接放行
        if (!StringUtils.hasText(token)){
            chain.doFilter(request,response);
            return;
        }
        //解析userId
        String userId = JwtUtils.parserJWT(token);
        //从redis中 获取用户信息
        LoginUser loginUser = (LoginUser)redisTemplate.opsForValue().get("login-"+userId);
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request,response);
    }
}
